<template>
	<view :data-theme="theme" class="container">
		<!-- 头部 -->
		<view style="background-color: #FFF;">
			<view class="card" style="padding-top: 40rpx;">
				<view style="display: flex;">
					<u--image :showLoading="true" :src="formModel.productDetail.image" width="80px"
						height="80px"></u--image>
					<view style="display: flex;flex-flow: column;flex: 1;margin: 6px 6px 0 6px;">
						<view class="u-line-1" style="font-size: 16px;font-weight: bold;">
							[{{brandName}}]{{formModel.productDetail.name}}</view>
						<view style="margin-top: 20rpx;color: #808080;">
							品牌 <view
								style="font-size: 12px;display: inline-block;font-weight: bold;color: #000;margin-left: 10rpx;">
								{{brandName}}
							</view>
						</view>
						<view style="margin-top: 20rpx;color: #808080;">
							商品编码<view
								style="font-size: 12px;display: inline-block;font-weight: bold;color: #000;margin-left: 10rpx;">
								{{formModel.productDetail.categoryId}}
							</view>
						</view>
					</view>
				</view>
			</view>
			<!-- tabs -->
			<!-- <u-tabs :list="list1" @click="tabsClick" :activeStyle="{color:bgColor}" :lineColor="bgColor"></u-tabs> -->
			<view style="padding-bottom: 10rpx;">
				<tab-bar style="background-color: #FFF;" :tabList="list1" :tabIndex.sync="innterIndex"
					@change="tabsClick"></tab-bar>
			</view>
		</view>
		<u--form labelPosition="left" :model="formModel" :rules="rules" ref="uForm"></u--form>
		<!-- 商品信息（封面加轮播图） -->
		<view v-if="innterIndex == 0" class="card" style="margin-top: 40rpx;padding: 10px 10px 0px;">
			<view class="product-title">商品主图</view>
			<span style="color: #808080;margin: 15rpx 0;display: inline-block;">商城商品信息顶部展示</span>
			<view style="display: flex;flex-flow: row wrap;">
				<u-upload style="flex: none;" :fileList="fileList1" @afterRead="afterRead" @delete="deletePic" name="1"
					:maxCount="1" uploadText="封面图"></u-upload>
			</view>

			<view class="product-title">商品轮播图</view>
			<span style="color: #808080;margin: 15rpx 0;display: inline-block;">商城商品中图片展示</span>
			<view style="display: flex;flex-flow: row wrap;">
				<u-upload style="flex: none;" :fileList="fileList2" @afterRead="afterRead" @delete="deletePic" name="2"
					multiple :maxCount="9" uploadText="轮播图"></u-upload>
			</view>

			<view class="product-title">商品详情图</view>
			<span style="color: #808080;margin: 15rpx 0;display: inline-block;">商城商品详情中图片展示</span>
			<view style="display: flex;flex-flow: row wrap;">
				<u-upload style="flex: none;" :fileList="fileList2" @afterRead="afterRead" @delete="deletePic" name="2"
					multiple :maxCount="9" uploadText="详情图"></u-upload>
			</view>


		</view>

		<!-- 商品简介 -->
		<view v-if="innterIndex == 1" class="card" style="margin-top: 40rpx;padding: 10px">
			<view class="product-title">商品简介</view>
			<u--textarea v-model="formModel.productDetail.intro" style="background-color: #f5f5f5 ;"
				placeholder="请输入商品简介" count maxlength="300" height="140"></u--textarea>
		</view>

		<view style="position: fixed;bottom: 0px;width: 100%;padding: 10px;background-color: #FFF;z-index: 999;">
			<!-- <u-button @click="submitProduct" style="font-weight: bold;border-radius: 10px;" :color="bgColor"
				size="large" type="primary" text="提交"></u-button> -->
			<button @click="submitProduct" class="bg_color"
				style="font-weight: bold;border-radius: 10px;color: #FFF;padding: 20rpx;" :color="bgColor">提交</button>
		</view>


	</view>
</template>

<script>
	import tabBar from '@/components/tab-bar/tab-bar.vue';
	import {
		brandlistApi,
	} from '@/api/category.js';
	import {
		productUpdateApi,
		productCreateApi,
		categoryApi,
		productGuaranteeApi,
		productDetailApi
	} from '@/api/product.js';
	import {
		setThemeColor
	} from '../../../utils/setTheme';
	let app = getApp();
	export default {
		components: {
			tabBar,
		},
		data() {
			return {
				bgColor: "#ffffff",
				theme: app.globalData.theme,
				id: 0, //商品ID
				specParamMap: {}, //规格参数
				sliderImages: [], //轮播图列表
				productCredentials: [], //资质图片
				skuArr: [], //商品规格
				fileList1: [
					// {
					// 	url:"https://p3.ssl.qhimg.com/t0137f6f23e234057d6.webp",
					// }
				], //商品封面图
				fileList2: [
					// {
					// 	url:"https://p4.ssl.qhimg.com/dr/90_0_85/t01ef6a992a4e4ce63c.webp",
					// }
				], //商品轮播图
				formModel: {
					productDetail: {
						image: "", //商品图片
						sliderImage: "", //轮播图
						cateId: "0", //商户商品分类id
						isSub: "false", //是否单独分佣
						attr: [], //商品属性ProductAttrAddRequest
						attrValue: [], //商品属性详情

						name: "", //商品名称
						intro: "", //商品简介
						brandId: "", //品牌
						categoryId: "", //平台商品分类id

					}, //商品详情
				},
				rules: {
					'productDetail.name': {
						type: 'string',
						required: true,
						message: '请填写商品名称',
						trigger: ['blur', 'change']
					},
					'productDetail.categoryId': {
						type: 'number',
						required: true,
						message: '请填写商品分类',
						trigger: ['blur', 'change']
					},
					'productDetail.brandId': {
						type: 'number',
						required: true,
						message: '请填写商品品牌',
						trigger: ['blur', 'change']
					},
					'productDetail.unitName': {
						type: 'string',
						required: true,
						message: '请填写商品单位',
						trigger: ['blur', 'change']
					},

				},
				list1: [{
					name: '商品图片',
					type: 0,
				}, {
					name: '商品描述',
					type: 1,
				}],
				innterIndex: 0, //tabs 索引,默认0
				renderedByHtml: false,
				brandData: [], //品牌名称集合
				brandName: '', //品牌名
			};
		},
		async onLoad(options) {
			this.bgColor = setThemeColor();
			uni.setNavigationBarColor({
				frontColor: '#ffffff',
				backgroundColor: this.bgColor,
			});
			if (options.id) {
				this.id = options.id;
			};
			if (options.id) {
				//加载商品详情
				this.getProductDetail();
			};
			this.getBrand();
		},
		methods: {
			//获取品牌id
			getBrand() {
				brandlistApi(this.brandForm).then((res) => {
					this.brandData = res.data.records.map(({
						id,
						name
					}) => ({
						id,
						name
					}));
				});
			},
			//标签点击索引
			tabsClick(item) {
				// this.innterIndex = item.type;
				this.innterIndex = item;
			},
			//提交商品
			submitProduct() {
				// 更新商品标识
				let isUpdate = parseFloat(this.id) > 0;
				// 校验数据
				let that = this;
				this.$refs.uForm.validate().then(res => {
					uni.$u.toast('1校验通过');
					//规格参数,规格属性,商品简介,运费模板，保障服务，商品详情*
					if (
						that.fileList1.length == 0 ||
						that.fileList2.length == 0 ||
						that.formModel.productDetail.intro == null || that.formModel.productDetail.intro.length ==
						0

					) {
						uni.$u.toast('请填写完整商品信息1！');
						return;
					}
					uni.$u.toast('2校验通过');
					// 同步表单数据
					that.getFormValue();
					// 提交表单
					uni.$u.toast('3提交表单');
					console.log(that.formModel.productDetail);
					let api = isUpdate ? productUpdateApi : productCreateApi;
					uni.showLoading({
						title: '保存中'
					});
					api(that.formModel.productDetail).then(res => {
							if (res.code == 200) {
								uni.$u.toast('保存成功！');
								//关闭当前页面
								setTimeout(() => {
									uni.navigateBack()
								}, 500);
							} else {
								console.log(res.msg);
								uni.$u.toast('保存失败！');
							}
						})
						.catch((res) => {
							console.log(res);
							uni.$u.toast('保存失败！' + res);
						})

				}).catch(errors => {
					console.log("submitProduct error", errors);
					uni.$u.toast('请填写完整商品信息！');
				})
			},
			//获取表单需要的值
			getFormValue() {
				let product = this.formModel.productDetail;
				product.image = this.fileList1[0].url;
				product.sliderImage = JSON.stringify(this.fileList2.map(item => item.url));
				// 同步 规格信息
				product.specType = true; //设置多规格
				// --------
				// attr | attrValue 
				// 验证是添加还是更新
				let attr = product.attr;
				let attrValuesList = [];
				// 校验skuArr和attrValue是否一个对象
				product.attrValue = this.skuArr;

				for (let s of this.skuArr) {
					let av = JSON.parse(s.attrValue);
					attrValuesList.push(av[this.attrKey]);
				}
				let attrValues = attrValuesList.join(',');
				if (attr.length == 0) {
					attr.push({
						attrName: this.attrKey,
						attrValues: attrValues
					});
				} else {
					attr[0].attrValues = attrValues;
				}
				this.$set(this.formModel, 'productDetail', product);

			},
			// 删除图片
			deletePic(event) {
				this[`fileList${event.name}`].splice(event.index, 1)
			},
			// 新增图片
			async afterRead(event) {
				// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file)
				let fileListLen = this[`fileList${event.name}`].length
				lists.map((item) => {
					this[`fileList${event.name}`].push({
						...item,
						status: 'uploading',
						message: '上传中'
					})
				})
				for (let i = 0; i < lists.length; i++) {
					const result = await this.uploadFilePromise(lists[i].url);
					if (result == null) {
						uni.showToast({
							title: "上传失败",
							icon: "none",
						})
						this.deletePic(event.index, 1);
						break;
					}
					let newStatus = {
						status: 'success',
						message: '上传成功',
						url: result,
					}
					let item = this[`fileList${event.name}`][fileListLen]
					this[`fileList${event.name}`].splice(fileListLen, 1, Object.assign(item, newStatus))
					fileListLen++
				}
			},
			uploadFilePromise(filePath) {
				return this.$util.uploadFilePromise(filePath, {
					url: 'upload/image',
					name: "multipart", //固定 multipart
					model: "product", //模块 用户user,商品product,微信wechat,news文章
					pid: 1, //分类ID 0编辑器,1商品图片,2拼团图片,3砍价图片,4秒杀图片,5文章图片,6组合数据图,7前台用户,8微信系列
					count: 1
				});
			},
			//查询商品详情
			async getProductDetail() {
				uni.showLoading({
					title: '加载中',
					mask: true
				});
				let that = this;
				await productDetailApi(this.id).then(res => {
					if (res.code == 200) {
						that.formModel.productDetail = res.data;
						that.skuArr = res.data.attrValue;
						// 格式化商品参数 specParam
						//商品规格参数
						that.$set(that, 'specParamMap', JSON.parse(res.data.specParam));
						//商品轮播图
						that.$set(that, 'sliderImages', JSON.parse(res.data.sliderImage));
						// 检测报告图
						that.$set(that, 'productCredentials', JSON.parse(res.data.productCredential));

						//--------------解析商品数据为表单数据
						that.fileList1 = [{
							url: res.data.image
						}];
						for (let image of that.sliderImages) {
							that.fileList2.push({
								url: image
							});
						}
					}
					uni.hideLoading();
					for (let i = 0; i < this.brandData.length; i++) {
						if (that.formModel.productDetail.brandId == this.brandData[i].id) {
							that.brandName = this.brandData[i].name;
							return;
						} else {
							that.brandName = '无品牌'
						}
					} //单位的回显
				}).catch(err => {
					console.log("getProductDetail error", err)
					uni.hideLoading();
				});
			},

		},
	}
</script>

<style lang="scss">
	// 动态颜色
	.bg_color {
		@include main_bg_color(theme);
	}

	.card {
		margin: 0 20rpx 20rpx 20rpx;
		background-color: #fff;
		border-radius: 20rpx;
	}

	// .container {
	// 	background-color: #fff;
	// }

	.product-title {
		font-size: 18px;
		font-weight: bold;
		margin-bottom: 20rpx;
		margin-top: 10rpx;
	}

	.u-content {
		padding: 24rpx;
		font-size: 32rpx;
		color: $u-content-color;
		line-height: 1.6;
	}
</style>